﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NCS.Library;
using NCS.Library.Components.Portal;
using NCS.Library.Components.Roles;
using NCS.Library.Components.Security;
using NCS.Library.Components.Users;
using NCS.Library.Utilities;
using NCS.Library.Components.Partner;
using System.Xml;

namespace Portal.Administrator.Users
{
    public partial class CreateUserDaiBieu : AuthenticatedControl
    {
        int userid = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Int32.TryParse(Request["uid"], out userid)) {
                userid = 0;
            }

            if (!this.IsPostBack)
            {
                this.loadCity();

                if (userid > 0)
                {
                    UserInfo userinfo = UserController.GetUser(userid);
                    if (userinfo == null)
                        userid = 0;
                    else
                    {
                        this.txtHoTen.Text = userinfo.DisplayName;
                        this.txtDiaChiCoQuan.Text = userinfo.Address1;
                        this.txtOtherJobs.Text = userinfo.OtherJobs;
                        this.dropCity.SelectedValue = userinfo.City.ToString();
                        this.txtEmail.Text = userinfo.Email;
                        this.txtFax.Text = userinfo.Fax;
                        this.txtPassword.Text = string.Empty;
                        this.txtPasswordConfirm.Text = string.Empty;

                        this.pnl_password.Visible = false;

                        this.txtTel.Text = userinfo.Tel;
                        this.txtUsername.Text = userinfo.Username;
                        this.txtUsername.ReadOnly = true;
                        this.radSex.SelectedValue = userinfo.Sex ? "1" : "0";
                        this.txtBirthDay.SetDate(userinfo.Birthday);
                        this.txtCoQuan.Text = userinfo.Agencies;
                        this.txtChucDanh.Text = userinfo.Titles;
                        string job = userinfo.Jobs;
                        #region load jobs
                        if (!string.IsNullOrEmpty(job))
                        {
                            string[] jobs = job.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string j in jobs)
                            {
                                switch (j)
                                {
                                    case "1":
                                        this.chk_BaoChi_TruyenHinh.Checked = true;
                                        break;
                                    case "2":
                                        this.chk_GiaoDuc.Checked = true;
                                        break;
                                    case "3":
                                        this.chk_KeToan_KiemToan_TaiChinh.Checked = true;
                                        break;
                                    case "4":
                                        this.chk_KhoaHoc_TinHoc_VienThong.Checked = true;
                                        break;
                                    case "5":
                                        this.chk_Luat.Checked = true;
                                        break;
                                    case "6":
                                        this.chk_NganHang_BaoHiem.Checked = true;
                                        break;
                                    case "7":
                                        this.chk_QuangCao_Maketing.Checked = true;
                                        break;
                                    case "8":
                                        this.chk_XayDung_KienTruc.Checked = true;
                                        break;
                                    case "9":
                                        this.chk_Yte_SucKhoe_MoiTruong.Checked = true;
                                        break;
                                    default: break;
                                }
                            }
                        }
                        #endregion load jobs
                    }
                }
                else
                {
                    this.txtBirthDay.SetDate(DateTime.Now);
                }
            }

        }

        private void loadCity()
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("Users/Province.xml"));
            XmlNodeList pros = xmldoc.DocumentElement.SelectNodes("./pro");

            this.dropCity.Items.Clear();

            for (int i = 0; i < pros.Count; i++) { 
                this.dropCity.Items.Add(new ListItem(pros[i].SelectSingleNode("./text()[1]").Value, (i+1).ToString()));
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (txtPassword.Text.Trim() != txtPasswordConfirm.Text.Trim()) {
                    this.lblUpdateStatus.Text = "Mật khẩu xác nhận không đúng";
                }

                try
                {
                    UserInfo user = null;
                    if (userid > 0)
                    {
                        user = UserController.GetUser(userid);
                    }

                    if (user == null)
                    {
                        user = new UserInfo();
                        userid = 0;
                    }

                    user.DisplayName = this.txtHoTen.Text;
                    user.Address1 = this.txtDiaChiCoQuan.Text;
                    user.OtherJobs = this.txtOtherJobs.Text;
                    user.City = Convert.ToInt32(this.dropCity.SelectedItem.Value);
                    user.Email = this.txtEmail.Text;
                    user.Fax = this.txtFax.Text;

                    if (userid == 0)
                        user.Password = SecurityMethod.MD5Encrypt(txtPassword.Text.Trim());
                    else if (this.txtPassword.Text.Length > 0)
                    {
                        user.Password = SecurityMethod.MD5Encrypt(txtPassword.Text.Trim());
                    }

                    user.Address2 = string.Empty;
                    user.Country = 0;
                    string[] ten = this.txtHoTen.Text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
                    user.FirstName = ten[ten.Length - 1];
                    user.LastName = this.txtHoTen.Text.Replace(user.FirstName, string.Empty);                    
                    user.IsAdmin = false;
                    user.Mobile = string.Empty;
                    user.IsSuperAdmin = false;                    
                    user.ZipCode = string.Empty;
                    user.PartnerID = 0;

                    user.Tel = this.txtTel.Text;
                    user.Username = this.txtUsername.Text;
                    user.UserType = 0;
                    user.Sex = this.radSex.SelectedItem.Value == "1" ? true : false;
                    user.Birthday = this.txtBirthDay.GetCurrentDate();
                    user.Agencies = this.txtCoQuan.Text;
                    user.Titles = this.txtChucDanh.Text;

                    string job = string.Empty;
                    if (this.chk_BaoChi_TruyenHinh.Checked)
                        job += "1,";
                    if (chk_GiaoDuc.Checked)
                        job += "2,";
                    if (chk_KeToan_KiemToan_TaiChinh.Checked)
                        job += "3,";
                    if (chk_KhoaHoc_TinHoc_VienThong.Checked)
                        job += "4,";
                    if (chk_Luat.Checked)
                        job += "5,";
                    if (chk_NganHang_BaoHiem.Checked)
                        job += "6,";
                    if (chk_QuangCao_Maketing.Checked)
                        job += "7,";
                    if (chk_XayDung_KienTruc.Checked)
                        job += "8,";
                    if (chk_Yte_SucKhoe_MoiTruong.Checked)
                        job += "9,";

                    if (job.Length == 0 && this.txtOtherJobs.Text.Length == 0)
                    {
                        this.lblUpdateStatus.Text = "Bạn cần chọn nghành nghề";
                        return;
                    }

                    user.Jobs = job.Remove(job.Length - 1, 1);

                    if (userid == 0)
                    {
                        userid = UserController.AddUser(user);
                        if (userid == 0)
                        {
                            lblUpdateStatus.Text = "Tên đăng nhập đã tồn tại";
                            return;
                        }
                        else
                        {
                            RoleController.AddUserToRole(userid, AppEnv.DEFAULT_ROLE, ConvertUtility.ToInt32(AppEnv.PortalId()));
                        }
                    }
                    else
                        UserController.UpdateUser(user);

                    if (userid > 0)
                    {
                        lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                        this.AddLog("User", " try create user " + txtUsername.Text + " success");
                    }
                    else
                        this.lblUpdateStatus.Text = "Cập nhật thất bại";
                }
                catch (Exception ex)
                {
                    //Response.Write(ex.Message);
                    this.lblUpdateStatus.Text = ex.Message;
                    this.AddLog("User", " try create user " + txtUsername.Text + " error: " + ex.Message);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(AppEnv.ADMIN_CMD + "usermanager");
        }
    }
}